#!/bin/bash
#
# Copyright 2011 Google Inc. All Rights Reserved.
# Author: sdd@google.com (Salvatore Domenick Desiano)
#
# Pushes changes from the issue clone into the push clone and then to
# the upstream repository. While this does not directly enforce code
# review rules, the developer is responsible for making sure the
# review is complete before running this script. This script cannot be
# run if any changes are pending in the edit clone or if any changes
# exist that have not been uploaded for review. See glp-common.sh for
# more information about the development process used by GLP
# developers.
#
# usage: src/scripts/glp-issue-push


# Read parameters and initialize variables.
source "$(dirname "${0}")/glp-common.sh"
glp::initialize_checkout_variables
if [[ "${ISSUE_STATE}" != 'active' ]]; then
    glp::die 'issue must be active'
fi
echo "Committing issue ${ISSUE_NUMBER}..."


# Push any changes from edit to issue clone (there should not be any,
# so bail if there are).
echo 'Updating review clones...'
glp::update_review_clones 'new_issue_rev' 'source: glp-issue-push'
if [[ "${new_issue_rev}" != "${ISSUE_REV}" ]]; then
    glp::die "code has changed since last issue update. please run \
glp-issue-update and have the code reviewed."
fi


# Confirm that review has been completed.
echo ''
echo 'Are you absolutely certain that the most recent versions of each file in this CL are:'
echo "  a) non-experimental and LGTM'd,"
echo '  b) in your experimental directory, or'
echo "  c) LGTM'd by the person whose experimental directory they are in,"
read -p 'yes or no? ' CONFIRM
if [[ "${CONFIRM}" != "yes" ]]; then
    echo "Well, if you're not sure, then I ain't doin nuthin."
fi
echo ''


echo "Creating push clone at ${PUSH_CLONE} from upstream clone..."
hg clone --quiet "${UPSTREAM_CLONE}" "${PUSH_CLONE}"
declare -r temp_edit_hgrc="$(mktemp -t glp-checkout)"
grep -v '^default' "${EDIT_CLONE}/.hg/hgrc" > "${temp_edit_hgrc}"
echo "default = ${HG_URL}" >> "${temp_edit_hgrc}"
mv -f "${temp_edit_hgrc}" "${EDIT_CLONE}/.hg/hgrc" || glp::die 'failure.'
rm -fr "${temp_edit_hgrc}"


echo 'Pushing changes from issue to push clone...'
glp::read_file "${ISSUE_MESSAGE_PATH}" log_message
glp::indirect_sync "${ISSUE_CLONE}" "${PUSH_CLONE}" "${log_message}"


echo 'Pushing changes from push clone to global repository...'
glp::hg_sync "${PUSH_CLONE}" "${HG_URL}"


echo 'Removing push clone...'
declare push_backup
glp::prefixed_path "${PUSH_CLONE}" "${ISSUE_NUMBER}." 'push_backup'
mv "${PUSH_CLONE}" "${push_backup}"
glp::warn "reccomend deleting ${push_backup}"


echo 'Pulling changes from global repository to upstream clone...'
glp::hg_sync "${HG_URL}" "${UPSTREAM_CLONE}"


echo 'Pulling changes from upstream to edit clone...'
glp::direct_sync "${UPSTREAM_CLONE}" "${EDIT_CLONE}"


echo 'Clearing review state...'
glp::reset_issue_state


echo "Issue ${ISSUE_NUMBER} pushed."
